package online.hxstar.cloud.web.controller;

import lombok.extern.slf4j.Slf4j;
import online.hxstar.cloud.web.annotation.UrlRegistered;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author xinghu
 * @version 1.0
 * @date 2019/11/14 1:52 下午
 */
@RestController
@Slf4j
public class UrlController {
	@Autowired
	WebApplicationContext applicationContext;

	@GetMapping("/getAllUrl")
	public List<String> getAllUrl() {
		RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
		//获取url与类和方法的对应信息
		Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();
		List<String> urlList = new ArrayList<>();
		for (Map.Entry<RequestMappingInfo, HandlerMethod> methodEntry : map.entrySet()) {
			if (methodEntry.getValue().hasMethodAnnotation(UrlRegistered.class)) {
				Set<String> patterns = methodEntry.getKey().getPatternsCondition().getPatterns();
				urlList.addAll(patterns);
			}
		}
		log.info("{}", urlList);
		return urlList;
	}
}
